package eu.irreality.dai.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

/**
 * Utility class to handle the parameters of the program.
 * 
 */
public class ConfigurationParametersManager
{

    private static Preferences prefs;

    private static final String CONFIGURATION_FILE = "ConfigurationParameters.properties";

    private static Map<Object, Object> defaultParameters;

    private ConfigurationParametersManager()
    {
    }

    public static String get(String key)
    {
	return getPrefs().get(key, (String) defaultParameters.get(key));
    }

    public static void put(String key, String value)
    {
	getPrefs().put(key, value);
    }

    public static void remove(String key)
    {
	getPrefs().remove(key);
    }

    public static void removeAll() throws BackingStoreException
    {
	getPrefs().removeNode();
	prefs = null;
    }

    private static Preferences getPrefs()
    {
	if (prefs == null)
	{
	    prefs = Preferences
		    .userNodeForPackage(ConfigurationParametersManager.class);
	}
	return prefs;
    }

    static
    {
	try
	{
	    /* Read property file (if exists). */
	    Class configurationParametersManagerClass = ConfigurationParametersManager.class;
	    ClassLoader classLoader = configurationParametersManagerClass
		    .getClassLoader();
	    InputStream inputStream = classLoader
		    .getResourceAsStream(CONFIGURATION_FILE);

	    if (inputStream == null)
	    {
		throw new FileNotFoundException("Configuration file '"
			+ CONFIGURATION_FILE + "' not found");
	    }

	    Properties properties = new Properties();
	    properties.load(inputStream);
	    inputStream.close();

	    defaultParameters = new HashMap<Object, Object>(properties);
	} catch (IOException e)
	{
	    // JOptionPane.showMessageDialog(null, e.getMessage(), "Error",
	    // JOptionPane.ERROR_MESSAGE);
	    e.printStackTrace();
	    System.exit(-1);
	}
    }

    /* Test code. Uncomment for testing. */
    // public static void main(String args[])
    // {
    // try
    // {
    // removeAll();
    // } catch (BackingStoreException e)
    // {
    // e.printStackTrace();
    // }
    // }
}
